// 云函数入口文件
const cloud = require('wx-server-sdk');
const TcbRouter = require('tcb-router');
const rp = require('request-promise');
cloud.init()
const db = cloud.database();
const blogCollection = db.collection('blog');
const MAX_LIMIT = 100;
// 云函数入口函数
exports.main = async (event, context) => {
  const app = new TcbRouter({
    event
  });
  //博客列表
  app.router("list", async (ctx, next) => {
    const keyword = event.keyword;
    let w = {}
    if (keyword.trim() != "") {
      w = {
        content: db.RegExp({
          regexp: keyword,
          options: 'i', // i 忽略大小学， m 换行匹配 
        })
      }
    }
    let blogList = await blogCollection.where(w).skip(event.start).limit(event.count)
      .orderBy('createTime', 'desc') // 逆序排序
      .get().then(res => {
        return res.data;
      })
    ctx.body = blogList;
  })
  //博客详情
  app.router("detail", async (ctx, next) => {
    const blogId = event.blogId;
    //详情查询
    let detail = await blogCollection.where({
      _id: blogId
    }).get().then(res => res.data)
    //评论查询
    let countResult = await blogCollection.count();
    const total = countResult.total;
    let commentList = {
      data: []
    }
    if (total > 0) {
      const batchTimes = Math.ceil(total / MAX_LIMIT);
      const tasks = [];
      for (let i = 0; i < batchTimes; i++) {
        let promise = db.collection("blog-comment").skip(i * MAX_LIMIT)
          .limit(MAX_LIMIT).where({
            blogId: blogId
          }).orderBy('createTime', 'desc').get()
        tasks.push(promise);
      }
      if (tasks.length > 0) {
        commentList = (await Promise.all(tasks)).reduce((acc, cur) => {
          return {
            data: acc.data.concat(cur.data)
          }
        })
      }
    }
    //返回结果
    ctx.body = {
      commentList,
      detail
    }
  })
  //获取我的发现
  app.router('getMyBlog', async (ctx, next) => {
    const _openid = cloud.getWXContext().OPENID;
    const result = await blogCollection.where({ _openid }).skip(event.start).limit(event.count).orderBy('createTime', 'desc').get().then(res => {
      return res.data;
    })
    ctx.body = result;
  })
  app.router('saylove',async (ctx, next) => {
    const res = await rp.get('https://api.tryto.cn/saylove/text');
    ctx.body = JSON.parse(res).data;
  })
  return app.serve()
}